package com.iursp.conf.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.iursp.domain.model.logger.ApiLogger;
import com.iursp.service.log.LoggerService;
import com.iursp.utils.MD5Util;

import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * @ClassName:  HttpAspect   
 * @Description: 使用aop记录请求信息 
 * @author: ruiwu
 * @date:   2018年6月29日 上午10:29:37   
 *
 */
@Aspect
@Component
public class HttpAspect {
	
	@Autowired
	private LoggerService loggerService;

    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);


    @Pointcut("execution(public * com.iursp.web.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //url method ip
        logger.info("利用AOP记录每次请求的有关信息，url={}，method={}，ip={}", request.getRequestURL(), request.getMethod(), request.getRemoteAddr());
        ApiLogger apiLogger = new ApiLogger();
        	apiLogger.setRequestIp(request.getRemoteAddr());
        	apiLogger.setRequestAddress(request.getRequestURL().toString());
        	apiLogger.setRequestType(request.getMethod());
        	Enumeration<String> names = request.getParameterNames();   //获取所有参数名称列表 
        	apiLogger.setRequestParameter(JSON.toJSONString(names));
        	
        	apiLogger.setLogLevel("info");
        	apiLogger.setSystemName(request.getContextPath());
        	apiLogger.setRequestNumber(MD5Util.encrypt());
        	apiLogger.setPerformTime(new Date());
        	loggerService.saveApiLogger(apiLogger);
        //类方法 参数
        logger.info("class_method={}, args={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(), joinPoint.getArgs());
    }

    @After("log()")
    public void doAfter() {
        logger.info("利用AOP记录每次请求完成后的信息");
    }

    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        logger.info("response={}", object.toString());
    }

}
